import requests, json
from datetime import datetime, timezone, timedelta
from dateutil import parser



def isodate2utcstamps(iso_date_time):
    # 将 ISO 8601 字符串转换为 datetime 对象
    dt = parser.parse(iso_date_time)
    timestamp = dt.timestamp()
    # print(timestamp)
    return timestamp


def get_image(harbor_url, repo_name, project_name, username, password):
    url = f"{harbor_url}/api/repositories/{repo_name}/{project_name}/tags?detail=1"
    response = requests.get(url, auth=(username, password))
    return response

# http://192.168.235.134:60195/api/repositories/demo/zookeeper/tags/3.9.5

def delete_image(harbor_url, repo_name, project_name, image_version, username, password):
    url = f"{harbor_url}/api/repositories/{repo_name}/{project_name}/tags/{image_version}"
    response = requests.delete(url, auth=(username, password))
    return response

#  http://192.168.235.134:60195/api/repositories/demo/zookeeper/tags?detail=1
# http://192.168.235.134:60195/api/repositories/demo/zookeeper/tags/3.9.5

# harbor_url = "http://harbor.irissz.com:60195"
# repo_name = "scmv6"
# project_name = "center-batch"
# username = "admin"
# password = "iris@Harbor2020"


# sorted_res1_list = sorted(res1_list, key=lambda x: x["created"])
# print("排序后的数组：")
# print(json.loads(sorted_res1_list))

# image_name = "fc9e35f"
#
# res2 = delete_image(harbor_url, repo_name, project_name, image_version, username, password)
# print(res2)



def main():
    harbor_url = "http://192.168.235.134:60195"
    repo_name = "demo"
    project_name = "center-merge"
    image_version = "504ee4b"
    username = "admin"
    password = "iris@Harbor2020"

    ninety_days_ago = datetime.now() - timedelta(days=90)

    timestamp_ninety_days_ago = ninety_days_ago.timestamp()

    print("90天前的时间戳:", timestamp_ninety_days_ago)

    # for digest in digests:
    res1_dic = {}
    res1 = get_image(harbor_url, repo_name, project_name, username, password)
    print(res1.text)
    res1_list = json.loads(res1.text)
    for res1_dic in res1_list:
        iso_date_time = res1_dic["created"]
        cur_timestamps = isodate2utcstamps(iso_date_time)
        if timestamp_ninety_days_ago > cur_timestamps:
            # delete_image(harbor_url, repo_name, project_name, image_version, username, password)
            print("镜像创建时间为：{}，镜像tag为：{}".format(iso_date_time, res1_dic["name"]))


if __name__ == '__main__':
    main()